from PyQt5.QtCore import Qt, pyqtSignal, QRect, QPoint
from PyQt5.QtGui import (QPainter, QPen)
from PyQt5.QtWidgets import (QMessageBox, QLabel)
from screeninfo import get_monitors


class CropLabel(QLabel):
    finish = pyqtSignal(tuple)

    def __init__(self, para, source_w, source_h):
        super().__init__(para)

        # 处理经过缩放的图片，记录缩放比例
        self.isScaled = False
        self.Scaling = 1.0
        monitor = get_monitors()[0]
        if source_h > monitor.height:
            self.isScaled = True
            self.Scaling = source_h / (monitor.height * 0.8)
        elif source_w > monitor.width:
            self.isScaled = True
            self.Scaling = source_w / (monitor.width * 0.8)

        self.setCursor(Qt.CrossCursor)
        self.setMouseTracking(False)

        # 设置起始点、结束点，以及它们画出的矩形
        self.StartPoint = QPoint()
        self.EndPoint = QPoint()
        self.rect = QRect()

    def paintEvent(self, event):
        painter = QPainter()
        painter.begin(self)
        painter.setPen(QPen(Qt.black, 3, Qt.DashLine))

        # 防止坐标超出边界
        if self.EndPoint.x() > self.width():
            self.EndPoint.setX(self.width() - 1)
        if self.EndPoint.x() < 0:
            self.EndPoint.setX(0)
        if self.EndPoint.y() > self.height():
            self.EndPoint.setY(self.height() - 1)
        if self.EndPoint.y() < 0:
            self.EndPoint.setY(0)

        self.rect = QRect(self.StartPoint, self.EndPoint).normalized()
        if self.rect.isValid():
            painter.drawRect(self.rect)

        painter.end()

    def mousePressEvent(self, event):
        self.StartPoint = QPoint(event.pos().x(), event.pos().y())

    def mouseMoveEvent(self, event):
        '''
            调用update()函数在这里相当于调用paintEvent()函数
            每次update()时，之前调用的paintEvent()留下的痕迹都会清空
        '''
        self.EndPoint = QPoint(event.pos().x(), event.pos().y())
        self.update()

    def mouseReleaseEvent(self, event):
        '''
            重写鼠标按住后松开的事件
        '''
        self.setCursor(Qt.ArrowCursor)
        self.EndPoint = QPoint(event.pos().x(), event.pos().y())
        self.update()
        if self.rect.isValid() and self.rect != QRect(0, 0, 1, 1):
            msg = QMessageBox()
            msg.setWindowTitle('Warning')
            msg.setText('Do you want to save the changes?')
            msg.setIcon(QMessageBox.Warning)
            msg.setStandardButtons(QMessageBox.Save | QMessageBox.Cancel)
            ret = msg.exec_()
            if ret == QMessageBox.Save:
                # 矩形的左、上、右、下边界
                boundary = [self.rect.topLeft().x(), self.rect.topLeft().y(),
                            self.rect.topLeft().x() + self.rect.width(),
                            self.rect.topLeft().y() + self.rect.height()]
                if self.isScaled:
                    boundary = [int(i * self.Scaling) for i in boundary]
                self.finish.emit(tuple(boundary))
        self.deleteLater()
